package com.lc.admin.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lc.admin.bean.LoginUserDetails;
import com.lc.admin.constants.RedisKeyConstants;
import com.lc.admin.utils.JwtUtil;
import com.lc.admin.utils.StringUtils;
import com.lc.admin.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${zhyl.securet}")
    private String securet;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuid = request.getHeader("Authorization");
        if(StringUtils.isEmpty(uuid)) {
            return true;
        }

        // 解析出token中的个人信息部门
        String token = redisTemplate.opsForValue().get(RedisKeyConstants.LOGIN_USER_TOKEN + uuid);
        Claims claims = JwtUtil.parseJWT(securet, token);
        String userJson = (String) claims.get("user");

        LoginUserDetails userDetails = JSONObject.parseObject(userJson, LoginUserDetails.class);

        // 存储到ThreadLocal
        String userJson2 = JSONObject.toJSONString(userDetails);
        UserThreadLocal.setSubject(userJson2);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("删除ThreadLocal中存储的数据");
        UserThreadLocal.removeSubject();
    }
}
